package org.wutopia.labcloud.domain.product.config.elasticsearch;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.transport.TransportUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;

@Configuration
public class ESClientConfig {

    @Value("${elasticsearch.uri}")
    private String serverUrl;

    @Value("${elasticsearch.username}")
    private String login;

    @Value("${elasticsearch.password}")
    private String apiKey;


    @Value("${elasticsearch.ca-path}")
    private String capath;

    @Bean
    public ElasticsearchClient getESClient() throws IOException {

        // URL and API key
//        String serverUrl = "https://localhost:9200";
//        String login = "elastic";
//        String apiKey = "0b5QJV0SIXyA0aomDgh-";

        InputStream input = Thread.currentThread()
                .getContextClassLoader()
                .getResourceAsStream(capath);

        SSLContext sslContext = TransportUtils.sslContextFromHttpCaCrt(input);


        return ElasticsearchClient.of(b -> b
                .host(serverUrl)
                .usernameAndPassword(login, apiKey)
                .sslContext(sslContext)
        );
    }

}
